package com.itcast.security.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcast.common.model.UserThreadLocal;
import com.itcast.common.model.dto.response.MemberResDTO;
import com.itcast.security.mapper.MemberMapper;
import com.itcast.security.model.Member;
import com.itcast.security.service.IMemberService;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 普通用户 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-11-02
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements IMemberService {
    /**
     * 默认头像
     */
    private static final String DEFAULT_AVATAR = "https://yjy-oss-videos.oss-accelerate.aliyuncs.com/tx.png";

    /**
     * 根据手机号查询普通用户
     *
     * @param phone 手机号
     * @return 普通用户
     */
    @Override
    public Member findByPhone(String phone) {
        LambdaQueryWrapper<Member> queryWrapper = Wrappers.<Member>lambdaQuery().eq(Member::getPhone, phone);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 新增普通用户
     *
     * @param openid 微信唯一标识
     * @param phone  手机号
     * @return 普通用户
     */
    @Override
    public Member add(String openid, String phone) {
        Member member = new Member();
        long id = IdUtil.getSnowflakeNextId();
        member.setId(id);

        String idStr = String.valueOf(id);
        member.setNickname("普通用户" + idStr.substring(idStr.length() - 4));

        if (CharSequenceUtil.isNotBlank(openid)) {
            member.setOpenid(openid);
        }

        member.setPhone(phone);
        //设置默认头像
        member.setAvatar(DEFAULT_AVATAR);
        baseMapper.insert(member);
        return member;
    }

    /**
     * 根据openId查询用户
     *
     * @param openId 微信唯一标识
     * @return 普通用户
     */
    @Override
    public Member getByOpenid(String openId) {
        return lambdaQuery().eq(Member::getOpenid, openId).one();
    }

    /**
     * 补充openid字段
     *
     * @param id     用户id
     * @param openId 微信唯一标识
     */
    @Override
    public void fillOpenid(Long id, String openId) {
        lambdaUpdate().eq(Member::getId, id).set(Member::getOpenid, openId).update();
    }

    /**
     * 查询用户信息
     *
     * @return 用户信息
     */
    @Override
    public MemberResDTO getInfo() {
        Long userId = UserThreadLocal.currentUserId();
        Member member = baseMapper.selectById(userId);
        return BeanUtil.toBean(member, MemberResDTO.class);
    }
}
